package com.pay.payment.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pay.common.constants.Constants;
import com.pay.common.model.RespEntity;
import com.pay.common.util.IpUtil;
import com.pay.modules.alipay.service.CpAliPayService;
import com.pay.payment.entity.Pay;
import com.pay.payment.entity.Product;
import com.pay.payment.service.IPayService;
import com.pay.payment.service.IProductService;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * <p>
 * 支付流水 前端控制器
 * </p>
 *
 * @author lengxingzi
 * @since 2021-12-24
 */
@RestController
@RequestMapping("/credit")
@Log4j2
public class CreditController {

    @Autowired
    IProductService productService;
    @Autowired
    IPayService payService;
    @Autowired
    CpAliPayService payBiz;

    @RequestMapping(value = "index", method={ RequestMethod.GET})
    public ModelAndView indexResult(HttpServletResponse response, HttpServletRequest request) {
        ModelAndView view =  new ModelAndView("credit/index");
        Map<String,Object> map = new HashMap<>();
        try {
            String ip = IpUtil.getIPAddress(request);
            String productId =  request.getParameter("pid");
            String userId =  request.getParameter("uid");
            if(StringUtils.isBlank(productId)||StringUtils.isBlank(userId)){
                map.put("message", "二维码失效");
                view = new ModelAndView("credit/401");
            }
            log.info("==========[InfoController]======index productId ={},userId ={}, ip={}",productId ,userId ,ip);
            map.put("pid",productId);
            map.put("uid",userId);
         //   view.addObject("pid",productId);
         //   view.addObject("uid",userId);
        } catch (Exception e) {
            log.error("==========[InfoController. Exception]->:{}",e);
            map.put("message", "操作异常");
            view = new ModelAndView("credit/500");
        }
        view.addAllObjects(map);
        return view;
    }

    @RequestMapping(value = "product/detail", method={ RequestMethod.POST})
    public RespEntity productDetail(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        String uid = request.getParameter("uid");
        String pid = request.getParameter("pid");
        log.info("==========[productDetail]======productId ={}",pid);

        try {
            JSONObject map = new JSONObject();
            QueryWrapper<Product> queryWrapper = new QueryWrapper();
            queryWrapper.eq("product_id", pid);
            queryWrapper.eq("status", 1);
            Product product = productService.getOne(queryWrapper);
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
            if(product != null){
                map.put("price",product.getPrice());
                log.info("==========[productDetail]======product ={}",product);
            }else {
                respEntity.setCode(Constants.Systems.PARAMS_INVALID);
                respEntity.setMsg("该产品已经下架，请联系销售人员");
            }
            respEntity.setData(map);
        } catch (Exception e) {
            log.error("==========[CustomerController. Exception]->:{}", e);
        }
        return respEntity;
    }


    @RequestMapping(value = "alipay/auth", method={ RequestMethod.POST})
    public RespEntity alipayAuth(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        Enumeration<String> enumeration = request.getParameterNames();
        Map<String,String> RDateArry = new TreeMap<String,String>();
        while(enumeration.hasMoreElements()) {
            String paraStr = enumeration.nextElement();
            if(paraStr != null){
                RDateArry.put(paraStr, request.getParameter(paraStr));//接收参数,（使用TreeMap自动排序）
            }
        }
        log.info("==========[alipayAuth]======RDateArry ={}",RDateArry);
        Integer cstId=1;
        Integer appId=1;

        Integer uid = Integer.valueOf(request.getParameter("uid"));
        Integer pid = Integer.valueOf(request.getParameter("pid"));
        String receiveName = request.getParameter("receiveName");
        String receiveMobile = request.getParameter("receiveMobile");
        String receiveAddress = request.getParameter("receiveAddress");
        String bId = request.getParameter("bId");
        QueryWrapper<Product> queryWrapper = new QueryWrapper();
        queryWrapper.eq("product_id", pid);
        queryWrapper.eq("status", 1);
        Product product = productService.getOne(queryWrapper);

        JSONObject jsonObject = payBiz.alipayOrderStr(bId,cstId,appId,pid,uid,product.getProductName(),receiveName,receiveMobile,receiveAddress,product.getPrice());
        if (jsonObject == null){
            respEntity.setCode(Constants.Systems.PARAMS_INVALID);
            respEntity.setMsg("订单异常");
        }else{
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setData(jsonObject);
        }
        log.info("==========[alipayAuth]======respEntity ={}",respEntity);
        return respEntity;
    }

    @RequestMapping(value = "order/complete", method={ RequestMethod.POST})
    public RespEntity orderComplete(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        log.info("==========[orderComplete]======seqNo ={}",request.getParameter("seqNo"));
        try {
            String seqNo = request.getParameter("seqNo");
            //支付状态(0= 申请成功 1=支付成功 2=支付中  3=支付失败 4=退货中 5=退货失败 6退货完成 7申请失败)
            boolean i =	payService.completePay(seqNo,0,2);
            if(i){
                log.info("==========[customer.orderComplete]======seqNo ={}状态处理成 支付中",seqNo);
            }
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
            respEntity.setData(i);
        } catch (Exception e) {
            log.error("==========[CustomerController. Exception]->:{}", e);
        }
        return respEntity;
    }


    @RequestMapping(value = "order/fail", method={ RequestMethod.POST})
    public RespEntity orderFail(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        log.info("==========[orderFail]======seqNo ={}",request.getParameter("seqNo"));
        try {
            String seqNo = request.getParameter("seqNo");
            //支付状态(0= 申请成功 1=支付成功 2=支付中  3=支付失败 4=退货中 5=退货失败 6退货完成 7申请失败)
            boolean i =	payService.completePay(seqNo,0,7);
            if(i){
                log.info("==========[customer.orderFail]======seqNo ={}状态处理成 支付失败",seqNo);
            }
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
            respEntity.setData(i);
        } catch (Exception e) {
            log.error("==========[CustomerController. Exception]->:{}", e);
        }
        return respEntity;
    }



    @RequestMapping(value = "user/fundAuthOrderUnFreeze", method={ RequestMethod.POST})
    public RespEntity fundAuthOrderUnFreeze(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        Integer cstId=1;
        String seqNo = request.getParameter("seqNo");
        QueryWrapper<Pay> qWrapper = new QueryWrapper();
        qWrapper.eq("seq_no", seqNo);
        Pay pay = payService.getOne(qWrapper);
        if(Objects.isNull(pay)){
            respEntity.setCode(Constants.Systems.PARAMS_INVALID);
            respEntity.setMsg("订单不存在");
            return respEntity;
        }
        String userId = pay.getParentId().toString();
        log.info("==========[userfundAuthOrderUnFreeze]====== pid ={}seqNo ={}",userId,seqNo);
        try {
            payBiz.fundAuthOrderUnFreeze(seqNo);
            //查询当前用户下的预支付成功的单子
            //支付状态(0= 申请成功 1=授权支付成功 2=授权支付中 3=授权支付失败 4=授权解冻中 5=授权解冻失败 6=授权解冻成功 7申请失败 8支付成功)
            QueryWrapper<Pay> queryWrapper = new QueryWrapper();
            queryWrapper.eq("cst_id", cstId);
            queryWrapper.eq("parent_id", userId);
            queryWrapper.eq("status", 1);
            List<Pay> payList = payService.list(queryWrapper);
            JSONObject map = new JSONObject();
            map.put("payList",payList);
            respEntity.setData(map);
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
        } catch (Exception e) {
            log.error("==========[OrderController. Exception]->:{}", e);
        }
        log.info("==========[userfundAuthOrderUnFreeze]======respEntity ={}",respEntity);
        return respEntity;
    }


    @RequestMapping(value = "user/tradePay", method={ RequestMethod.POST})
    public RespEntity tradePay(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        Integer cstId=1;
        String seqNo = request.getParameter("seqNo");
        QueryWrapper<Pay> qWrapper = new QueryWrapper();
        qWrapper.eq("seq_no", seqNo);
        Pay pay = payService.getOne(qWrapper);
        if(Objects.isNull(pay)){
            respEntity.setCode(Constants.Systems.PARAMS_INVALID);
            respEntity.setMsg("订单不存在");
            return respEntity;
        }
        String userId = pay.getParentId().toString();
        log.info("==========[usertradePay]====== pid ={} seqNo ={}",userId,seqNo);
        try {
            payBiz.tradePay(seqNo);
            //查询当前用户下的预支付成功的单子
            //支付状态(0= 申请成功 1=授权支付成功 2=授权支付中 3=授权支付失败 4=授权解冻中 5=授权解冻失败 6=授权解冻成功 7申请失败 8支付成功)
            QueryWrapper<Pay> queryWrapper = new QueryWrapper();
            queryWrapper.eq("cst_id", cstId);
            queryWrapper.eq("parent_id", userId);
            queryWrapper.eq("status", 1);
            List<Pay> payList = payService.list(queryWrapper);
            JSONObject map = new JSONObject();
            map.put("payList",payList);
            respEntity.setData(map);
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
        } catch (Exception e) {
            log.error("==========[OrderController. Exception]->:{}", e);
        }
        log.info("==========[usertradePay]======respEntity ={}",respEntity);
        return respEntity;
    }


    @RequestMapping(value = "user/payStatus", method={ RequestMethod.POST})
    public RespEntity payStatus(HttpServletResponse response, HttpServletRequest request) {
        RespEntity respEntity = new RespEntity(Constants.Systems.FAIL,Constants.Systems.SYSTEM_ERROR_CODE);
        Integer cstId=1;
        String payStatus = request.getParameter("payStatus");
        String userId = request.getParameter("userId");
        log.info("==========[userpayStatus]====== pid ={} payStatus ={}",userId,payStatus);
        try {
            QueryWrapper<Pay> queryWrapper = new QueryWrapper();
            queryWrapper.eq("cst_id", cstId);
            queryWrapper.eq("parent_id", userId);
            queryWrapper.eq("status", payStatus);
            List<Pay> payList = payService.list(queryWrapper);
            JSONObject map = new JSONObject();
            map.put("payList",payList);
            respEntity.setData(map);
            respEntity.setStatus(Constants.Systems.OK);
            respEntity.setCode(Constants.Systems.SERVER_SUCCESS);
        } catch (Exception e) {
            log.error("==========[OrderController. Exception]->:{}", e);
        }
        log.info("==========[userpayStatus]======respEntity ={}",respEntity.toString());
        return respEntity;
    }



}
